package com.handinglian.ai.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.handinglian.ai.common.dto.ResultData;
import com.handinglian.ai.common.shiro.CustomFormAuthenticationFilter;
import com.handinglian.ai.system.service.LoginService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Service
public class LoginServiceImpl implements LoginService {
    @Override
    public ResultData login(HttpServletRequest request, HttpServletResponse response) {
        Subject subject = SecurityUtils.getSubject();

        // 如果已经登录，返回登录成功
        if (subject.isAuthenticated()) {
            HttpSession httpSession  = request.getSession(false);
            String jessionId = null;
            if (httpSession != null){
                jessionId = httpSession.getId();
            }

            return ResultData.success(jessionId, "登录成功！！");
        }

        //登录失败返回
        String message = (String)request.getAttribute(CustomFormAuthenticationFilter.DEFAULT_MESSAGE_PARAM);
        return ResultData.loginFailure(message);
    }

    @Override
    public ResultData getJSessionId(HttpServletRequest request) {
        HttpSession httpSession  = request.getSession(false);
        if (httpSession == null){
            return ResultData.success(null);
        } else {
            return ResultData.success(httpSession.getId());
        }
    }
}
